<?php

namespace MoChat\App\Statistic\Command;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;
use MoChat\App\Client\Model\Client;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use TheSeer\Tokenizer\Exception;
use Hyperf\Command\Annotation\Command;

/**
 * 原客户数
 * @Command
 */
class OriginalClientCommand extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        parent::__construct('originalClient');
    }

    public function configure()
    {
        parent::configure();
        $this->addOption('clear', 'C', InputArgument::OPTIONAL, '清除redis', 0);
        $this->setDescription('原客户数处理');
    }

    public function handle()
    {
        $clients = Db::table('work_employee as employee')
            ->leftJoin('client as client', 'employee.id', '=', 'client.work_employee_id')
            ->select([
                Db::raw('COUNT(mc_client.id) as client_number'),
                'employee.id as work_employee_id'
            ])
            ->where('client.created_at','<','2023-09-07 00:00:00')
            ->groupBy(['employee.id'])
            ->get();
        $clients || $clients = collect([]);
        $clients = $clients->toArray();
        if (!empty($clients)) {
            $data=[];
            $date=date('Y-m-d H:i:s');
            foreach ($clients as $client){
                $data[] = [
                    'work_employee_id' => $client->work_employee_id,
                    'client_number' => $client->client_number,
                    'created_at' => $date
                ];
            }
            if (!empty($data)){
                Db::table('original_client_employee')->delete();
                Db::table('original_client_employee')->insert($data);
            }
        }
        $this->line('客户绑定任务脚本处理完成', 'info');

    }
}
